using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.WarehouseManage;
using ProduceBasicData.Api.DTO.WarehouseDto;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using System.Threading;
using System.Threading.Tasks;

namespace ProduceBasicData.Api.Application.Handler.WarehouseManage
{
    /// <summary>
    /// 获取单个入库单明细处理器
    /// </summary>
    public class GetStockInOrderByIdHandler : IRequestHandler<GetStockInOrderByIdCommand, ApiResult<List<StockInOrderItemDto>>>
    {
        private readonly IBaseRespository<StockInOrderItem> _stockInOrderItemRepository;
        private readonly IMapper _mapper;

        public GetStockInOrderByIdHandler(IBaseRespository<StockInOrderItem> stockInOrderItemRepository, IMapper mapper)
        {
            _stockInOrderItemRepository = stockInOrderItemRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理获取单个入库单明细请求
        /// </summary>
        /// <param name="request">获取单个入库单明细命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>入库单明细结果</returns>
        public async Task<ApiResult<List<StockInOrderItemDto>>> Handle(GetStockInOrderByIdCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<StockInOrderItemDto>>();

            try
            {
                // 根据ID获取入库单明细列表
                var stockInOrderItems = await _stockInOrderItemRepository.GetAllAsync(x => x.StockInOrderId == request.Id);

                if (stockInOrderItems == null || stockInOrderItems.Count == 0)
                {
                    result.Code = ApiEnum.Failed;
                    result.Msg = "未找到入库单明细信息";
                    result.Data = new List<StockInOrderItemDto>(); // 返回空列表而不是null
                    return result;
                }

                // 映射到DTO列表
                var stockInOrderItemDtos = _mapper.Map<List<StockInOrderItemDto>>(stockInOrderItems);

                result.Code = ApiEnum.Success;
                result.Msg = "查询成功";
                result.Data = stockInOrderItemDtos;
            }
            catch (Exception ex)
            {
                // 记录日志（实际项目中应使用专门的日志组件）
                // logger.LogError(ex, "获取入库单明细异常");

                result.Code = ApiEnum.Failed;
                result.Msg = $"查询异常: {ex.Message}";
                result.Data = new List<StockInOrderItemDto>(); // 即使异常也返回空列表而不是null
            }

            return result;
        }
    }
}